package com.example.cmh.service.impl;

import com.example.cmh.common.CustomException;
import com.example.cmh.common.PageResult;
import com.example.cmh.common.Result;
import com.example.cmh.mapper.NewsMapper;
import com.example.cmh.pojo.News;
import com.example.cmh.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class NewsServiceImpl implements NewsService {

    @Autowired
    private NewsMapper newsMapper;

    @Override
    @Transactional
    public Result<String> addNews(News news, Integer currentUserId) throws CustomException {
        if (news.getNewsTitle() == null || news.getNewsTitle().trim().isEmpty()) {
            throw new CustomException("新闻标题不能为空");
        }
        if (news.getNewsContent() == null || news.getNewsContent().trim().isEmpty()) {
            throw new CustomException("新闻内容不能为空");
        }
        if (news.getNewsSummary() == null || news.getNewsSummary().trim().isEmpty()) {
            throw new CustomException("新闻简介不能为空");
        }
        if (news.getNewsImagePath() == null || news.getNewsImagePath().trim().isEmpty()) {
            throw new CustomException("新闻图片不能为空");
        }
        if (news.getAuthor() == null || news.getAuthor().trim().isEmpty()) {
            throw new CustomException("作者不能为空");
        }
        
        // 设置创建者ID
        news.setCreatPersonId(currentUserId);
        
        // 设置审核状态：管理员(ID=1)自动通过，其他用户需要审核
        if (currentUserId != null && currentUserId == 1) {
            news.setNewsStatus(1); // 已审核
        } else {
            news.setNewsStatus(0); // 未审核
        }
        
        int result = newsMapper.insert(news);
        if (result > 0) {
            return Result.success("新增新闻成功", "success");
        } else {
            throw new CustomException("新增新闻失败");
        }
    }

    @Override
    @Transactional
    public Result<String> updateNews(Boolean isAdmin, News news) throws CustomException {
        if (news.getNewsId() == null) {
            throw new CustomException("新闻ID不能为空");
        }
        if (news.getNewsTitle() == null || news.getNewsTitle().trim().isEmpty()) {
            throw new CustomException("新闻标题不能为空");
        }
        if (news.getNewsContent() == null || news.getNewsContent().trim().isEmpty()) {
            throw new CustomException("新闻内容不能为空");
        }
        if (news.getNewsSummary() == null || news.getNewsSummary().trim().isEmpty()) {
            throw new CustomException("新闻简介不能为空");
        }
        if (news.getNewsImagePath() == null || news.getNewsImagePath().trim().isEmpty()) {
            throw new CustomException("新闻图片不能为空");
        }
        if (news.getAuthor() == null || news.getAuthor().trim().isEmpty()) {
            throw new CustomException("作者不能为空");
        }
        News old = newsMapper.selectById(news.getNewsId());
        if (old == null) {
            throw new CustomException("新闻不存在");
        }
        if(isAdmin){
            news.setNewsStatus(1);
        }
        else news.setNewsStatus(0);
        // 权限校验（如有登录用户信息可补充）
        int result = newsMapper.updateById(news);
        if (result > 0) {
            return Result.success("修改新闻成功", "success");
        } else {
            throw new CustomException("修改新闻失败");
        }
    }

    @Override
    @Transactional
    public Result<String> deleteNews(Integer newsId) throws CustomException {
        if (newsId == null) {
            throw new CustomException("新闻ID不能为空");
        }
        News old = newsMapper.selectById(newsId);
        if (old == null) {
            throw new CustomException("新闻不存在");
        }
        int result = newsMapper.deleteById(newsId);
        if (result > 0) {
            return Result.success("删除新闻成功", "success");
        } else {
            throw new CustomException("删除新闻失败");
        }
    }

    @Override
    public Result<List<News>> searchNews(String newsTitle, String author, String newsSummary, String newsImagePath, Integer currentUserId) throws CustomException {
        List<News> list = newsMapper.selectByCondition(newsTitle, author, newsSummary, newsImagePath);
        
        // 过滤未审核的新闻（普通用户只能看到自己的未审核新闻）
        if (currentUserId != null && currentUserId != 1) {
            list.removeIf(news -> news.getNewsStatus() == 0 && !news.getCreatPersonId().equals(currentUserId));
        }
        
        return Result.success(list);
    }

    @Override
    public Result<News> getNewsDetail(Integer newsId) throws CustomException {
        if (newsId == null) {
            throw new CustomException("新闻ID不能为空");
        }
        News news = newsMapper.selectById(newsId);
        if (news == null) {
            throw new CustomException("新闻不存在");
        }
        return Result.success(news);
    }
    
    @Override
    public Result<PageResult<News>> getNewsListWithPage(String newsTitle, String author, String newsSummary, Integer currentUserId, Integer current) throws CustomException {
        if (current == null || current < 1) {
            current = 1;
        }
        
        int pageSize = 10; // 固定每页10条
        int offset = (current - 1) * pageSize;
        
        // 确定查询条件
        Integer newsStatus = null;
        Integer creatPersonId = null;
        
        if (currentUserId != null && currentUserId != 1) {
            // 普通用户：只显示已审核的新闻或自己创建的创建的新闻
            newsStatus = 1; // 已审核
            creatPersonId = currentUserId; // 自己创建的新闻
        }
        // 管理员(currentUserId=1或null)可以看到所有新闻
        
        List<News> newsList = newsMapper.selectWithPage(newsTitle, author, newsSummary, newsStatus, creatPersonId, offset, pageSize);
        long total = newsMapper.count(newsTitle, author, newsStatus, creatPersonId);

        PageResult<News> pageResult = new PageResult<>();
        pageResult.setRecords(newsList);
        pageResult.setTotal(total);
        pageResult.setCurrent(current);
        pageResult.setSize(pageSize);
        pageResult.setPages((int) Math.ceil((double) total / pageSize));
        
        return Result.success(pageResult);
    }
    
    @Override
    @Transactional
    public Result<String> reviewNews(Integer newsId, Integer status) throws CustomException {
        if (newsId == null) {
            throw new CustomException("新闻ID不能为空");
        }
        if (status == null || (status != 1 && status != 2)) {
            throw new CustomException("审核状态无效，1表示通过，2表示拒绝");
        }
        
        News news = newsMapper.selectById(newsId);
        if (news == null) {
            throw new CustomException("新闻不存在");
        }
        
        int result = newsMapper.updateStatus(newsId, status);
        if (result > 0) {
            String message = status == 1 ? "审核通过成功" : "审核拒绝成功";
            return Result.success(message, "success");
        } else {
            throw new CustomException("审核操作失败");
        }
    }
} 